package com.seari.custody.service.Impl;

import cn.hutool.core.util.IdUtil;
import com.google.api.client.util.ArrayMap;
import com.seari.custody.bean.User;
import com.seari.custody.bean.UserDTO;
import com.seari.custody.bean.UserPersonalCenter;
import com.seari.custody.component.MinIoUtil;
import com.seari.custody.component.WebserviceClient;
import com.seari.custody.config.CaffeineConfig;
import com.seari.custody.mapper.UserMapper;
import com.seari.custody.service.UserService;
import com.seari.custody.util.EncryptUtils;
import com.seari.custody.util.JwtTokenUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebserviceClient webserviceClient;
    @Autowired
    private MinIoUtil minIoUtil;

    @Value("${iconImg.defaultAddress}")
    private String defaultAddress;

    @Value("${iconImg.defaultAvatar}")
    private String defaultAvatar;


    @Override
    @CacheEvict(cacheNames = CaffeineConfig.USERS, allEntries = true)

    public void save(User user) throws Exception {
        webserviceClient.addUserinfo(user.getUsername());

        user.setUuid(IdUtil.objectId());
        user.setPassword(EncryptUtils.encode(user.getPassword()));

        userMapper.save(user);
    }

    @SneakyThrows
    public static void main(String[] args) {
        System.out.println(EncryptUtils.encode("qwer1234"));
    }

    @Override
    public List<User> getUserFoByToken(User id) {
        return userMapper.getUserFoByToken(id);
    }

    @Override
    public User getInfo(String token) {

        String userNumber = JwtTokenUtils.getUserNumber(token.substring(JwtTokenUtils.TOKEN_PREFIX.length()));

        User userByUsername = userMapper.findUserByUsername(userNumber);


        return userByUsername;
    }

    @Override
    public Map<String, User> getUser() {
        return null;
    }

    @Override
    @CacheEvict(cacheNames = CaffeineConfig.USERS, allEntries = true)

    public Integer addUser(User add) {
        return userMapper.addUser(add);
    }

    @Override
    @CacheEvict(cacheNames = CaffeineConfig.USERS, allEntries = true)

    public int updateUser(Map<String, Object> params) {
        return userMapper.updateUser(params);
    }

    @Override
    @CacheEvict(cacheNames = CaffeineConfig.USERS, allEntries = true)
    public int deleteUser(String id) {
        return userMapper.deleteUser(id);
    }

    @Override
    public List<UserDTO> getAllUsers() {
        return userMapper.getAllUsers();
    }

    @Override
    public List<UserDTO> qryUserByName(String userName) {
        return userMapper.qryUserByName(userName);
    }

    @Override
    public User qryUserById(String username) throws Exception {
        User user = userMapper.qryUserById(username);
        String password = user.getPassword();
        user.setPassword(EncryptUtils.decode(password));
        user.setEmail(user.getEmail());
        return user;
    }

    @Override
    public User qryUserByNumber(String number) {
        return userMapper.qryUserByNumber(number);
    }

    @Override
    @Cacheable(keyGenerator = "myKeyGenerator", cacheNames = CaffeineConfig.USERS, sync = true)
    public String qryNameByUserNumber(String number) {
        return userMapper.qryNameIdByNumber(number);
    }

    @Override
    public void updatePersonalCenter(String usernumber, String username, String phone, String email, String password1) throws Exception {
        Map<String, Object> map = new ArrayMap<>();
        map.put("password", password1 == "" ? "" : EncryptUtils.encode(password1));
        map.put("userNumber", usernumber);
        map.put("username", username);
        map.put("phone", phone);
        map.put("email", email);
        userMapper.updatepersonalById(map);
    }

    @Override
    public void updatePersonalCenter(MultipartFile file, String usernumber, String username, String phone, String email, String password1) throws Exception {
        String name = file.getOriginalFilename();
        byte[] byteArr = file.getBytes();
        InputStream inputStream = new ByteArrayInputStream(byteArr);
        String contentType = "image/jpeg";
        minIoUtil.putObject("projectimg", name, inputStream, contentType);
        Map<String, Object> map = new ArrayMap<>();

        if(password1!= null && password1.length() != 0){
            map.put("password", EncryptUtils.encode(password1));
        }else{
            map.put("password", "");
        }
        map.put("userNumber", usernumber);
        map.put("username", username);
        map.put("phone", phone);
        map.put("email", email);
        map.put("iconimage", name);
        userMapper.updatepersonalById(map);
    }

    @Override
    public UserPersonalCenter personalById(String username) throws Exception {
        UserPersonalCenter user = userMapper.personalById(username);
        user.setEmail(user.getEmail());
        return user;
    }

    @Override
    public String headportraitImg(String username) {
        String s = userMapper.iconImgServer(username);
        String iconImg;
        if(s != null && s.length() != 0) {
             iconImg=defaultAddress+s;
        }else{
             iconImg=defaultAvatar;
        }
        return iconImg;
    }
}